<template>
  <basic-dialog
    :visible="dialogVisible"
    :title="title"
    :show-footer="false"
    :width="'85%'"
    :handleClose="handleCloseDialog"
    :handleOpen="handleOpenDialog"
  >
    <el-row>
      <el-col :span="12" class="left-col">
        <div class="category-search">
          <el-form size="mini" ref="formData" :model="formData" inline>
            <el-form-item prop="categoryName" label="名称">
              <el-input
                placeholder="请输入品类名称"
                v-model="formData.categoryName"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item prop="categoryName" label="编码">
              <el-input
                placeholder="请输入四级类编码"
                v-model="formData.categoryNo"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSerach">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="divider" content-position="left">条件查询结果：</el-divider>
        <div class="category-searchlist">
          <el-checkbox-group v-model="searchList.checkList" v-loading="searchLoading">
            <el-checkbox
              v-for="item in searchList.dataSource"
              :label="item.categoryUuid"
              :key="item.categoryUuid"
              @change="(val) => { handleCheckSearchList(val, item) }"
            >
            {{ item.categoryPath }}&nbsp;&nbsp;{{ item.categoryNo }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-divider class="divider" content-position="left">品类树选择：</el-divider>
        <div class="category-tree">
          <el-tree
            v-loading="treeLoading"
            ref="elTree"
            lazy
            accordion
            show-checkbox
            :node-key="elTree.nodeKey"
            :data="elTree.dataSource"
            :props="elTree.props"
            :load="loadElTreeNode"
            @check="getCheckedNodes"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="selected-card"  v-loading="tagLoading">
          <div>
            <span>已选品类</span>
            <div style="float: right;">
              <el-button
                v-show="selectCategoryList.length"
                type="text"
                @click="handleClear"
              >一键清空</el-button>
              <el-button
                type="text"
                @click="handleSubmit"
                :loading="submitLoading"
              >提交</el-button>
            </div>
          </div>
          <el-divider class="divider" />
          <el-tag
            class="category-tag"
            v-for="tag in selectCategoryList"
            :key="tag.categoryUuid"
            closable
            :disable-transitions="false"
            effect="plain"
            @close="handleRemoveCategory(tag, true)">
            <span class="tag-text">{{tag.categoryPath}} {{tag.categoryNo}}</span>
          </el-tag>
        </div>
      </el-col>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import { ApiRequest } from '@api/basePage';
import { isResponseSuccess } from '@/utils/bizUtils';

export default {
  name: 'LinkCategoryDialog',
  components: {
    BasicDialog,
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    materialId: {
      type: Number,
      default: null
    },
    materialName: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      submitLoading: false,
      searchLoading: false,
      treeLoading: false,
      tagLoading: false,
      selectCategoryList: [], // 已选品类集合
      searchCategoryList: [], // 条件查询选择集合
      treeCategoryList: [], // 品类树选择集合
      elTree: {
        dataSource: [], // 数据源
        props: {
          children: 'children',
          label: 'cateNameAndNoStr',
          disabled: 'disabled',
          isLeaf: 'leaf',
          checked: false
        },
        nodeKey: 'categoryNo',
        END_LEVEL: '4',
      },
      formData: {
        categoryName: '',
        categoryNo: '',
      },
      searchList: { // 查询列表
        dataSource: [], // 数据源
        checkList: [], // 勾选对象
      },
      apiObj: {
        getCategoryList: { // 查询一级分类接口
          url: '/sysback/choose/category/getByParentUuids',
          type: 'post'
        },
        // 按条件查询品类
        getCategoryListByKey: {
          url: '/sysback/choose/category/searchCategoryList',
          type: 'post'
        },
        // 提交关联品类
        submitSelectCategory: {
          url: '/sysback/product/rawMaterial/addCategoryRel',
          type: 'post'
        },
        // 查询已关联关联品类
        getSelectCategory: {
          url: '/sysback/product/rawMaterial/queryCategoryRel',
          type: 'post'
        },
      }
    };
  },
  computed: {
    dialogVisible () {
      return this.visible;
    },
    id () {
      return this.materialId;
    },
    title () {
      return `原材料(${this.materialName})关联品类`
    }
  },
  watch: {
    searchCategoryList: {
      handler (val) {
        this.generateLinkData()
      },
      deep: true
    },
    treeCategoryList: {
      handler (val) {
        this.generateLinkData()
      },
      deep: true
    },
  },
  methods: {
    // 表单-分类名称查询
    async handleSerach () {
      const data = {};
      const { categoryNo, categoryName } = this.formData;
      if (!categoryNo && !categoryName) {
        this.$message.warning('品类名称和品类编码不能同时为空');
        return false;
      }
      const { url, type } = this.apiObj.getCategoryListByKey;
      const param = categoryNo ? `categoryNo=${categoryNo}` : `categoryName=${categoryName}`;
      const apiUrl = `${url}?${param}`;
      this.searchLoading = true;
      const res = await ApiRequest(apiUrl, type, data, true);
      this.searchLoading = false;
      if (isResponseSuccess(res)) {
        this.searchList.checkList = [];
        this.searchList.dataSource = res.retData;
      }
    },
    // 查询已关联分类
    async getSelectedCategoryAction () {
      try {
        const data = { id: this.id };
        const { url, type } = this.apiObj.getSelectCategory;
        this.tagLoading = true;
        const res = await ApiRequest(url, type, data);
        this.tagLoading = false;
        if (isResponseSuccess(res)) {
          this.searchCategoryList = res.retData;
        }
      } catch (err) {
        this.tagLoading = false;
      }
    },
    // 查询一级分类
    async getLevelOneCategoryListFn () {
      const data = ['systemUuid'];
      const { url, type } = this.apiObj.getCategoryList;
      this.treeLoading = true;
      const res = await ApiRequest(url, type, data);
      this.treeLoading = false;
      if (!isResponseSuccess(res)) {
        return false;
      }
      this.elTree.dataSource = this.formatElTreeData(res.retData);
    },
    // 根据父分类查询子分类
    async getByParentUuidFn (categoryUuids) {
      const data = categoryUuids
      const { url, type } = this.apiObj.getCategoryList;
      const res = await ApiRequest(url, type, data);
      if (!isResponseSuccess(res)) {
        return false;
      }
      return res.retData;
    },
    // 加载el-tree节点
    loadElTreeNode (node, resolve) {
      if (node.level === 0) {
        return false;
      }
      const { categoryUuid } = node.data;
      this.getByParentUuidFn([categoryUuid]).then(retData => {
        resolve(this.formatElTreeData(retData));
      })
    },
    // 格式化el-tree数据
    formatElTreeData (list = []) {
      return list.map(item => ({
        ...item,
        disabled: item.levelNum === '1' || item.levelNum === '2',
        leaf: item.levelNum === this.elTree.END_LEVEL
      }));
    },
    // 勾选分类查询结果列表
    handleCheckSearchList (val, data) {
      if (val) {
        if (this.searchCategoryList.some(item => item.categoryUuid == data.categoryUuid)) {
          return;
        }
        this.searchCategoryList.push(data)
      } else {
        this.handleRemoveCategory(data)
      }
    },
    // 取消品类选择
    handleRemoveCategory (data, isTag) {
      this.searchCategoryList = this.searchCategoryList.filter(item => item.categoryUuid != data.categoryUuid)
      this.treeCategoryList = this.treeCategoryList.filter(item => item.categoryUuid != data.categoryUuid)
      if (isTag) {
        this.searchList.checkList = this.searchList.checkList.filter(item => item != data.categoryUuid)
        this.$refs.elTree.setChecked(data[this.elTree.nodeKey], false);
      }
    },
    // 勾选树节点
    getCheckedNodes (current, checked) {
      const { checkedNodes } = checked;
      const level4List = checkedNodes.filter(item => item.levelNum == 4)
      const uuids = checkedNodes.filter(item => item.levelNum == 3).map(item => item.categoryUuid)
      if (uuids.length != 0) {
        this.getByParentUuidFn(uuids).then(retData => {
          this.treeCategoryList = _.uniqBy(level4List.concat(retData), this.elTree.nodeKey)
        })
      } else {
        this.treeCategoryList = _.uniqBy(level4List.concat([]), this.elTree.nodeKey)
      }
    },
    // 清空选择结果
    handleClear () {
      this.$confirm('确定后将清空所有已选四级分类，您确认吗？', '清空', {
        type: 'warning',
      }).then(() => {
        this.handleClearCategory()
      }).catch(() => {});
    },
    // 清空所有已勾选节点的勾选状态
    clearAllCheckedNodes () {
      this.$refs.elTree.setCheckedKeys([]); // 全部取消el-tree勾选节点
    },
    // 关闭所有已展开节点
    closeAllExpandNodes () {
      var nodes = this.$refs.elTree.store.nodesMap;
      for (let i in nodes) {
        nodes[i].expanded = false;
      }
    },
    // 组合已关联数据
    generateLinkData () {
      this.selectCategoryList = _.uniqBy(this.searchCategoryList.concat(this.treeCategoryList), this.elTree.nodeKey)
    },
    handleSubmit () {
      const data = {
        id: this.id,
        categoryUuidList: this.selectCategoryList.map(item => item.categoryUuid)
      }
      const { url, type } = this.apiObj.submitSelectCategory;
      this.submitLoading = true;
      ApiRequest(url, type, data).then((res) => {
        this.submitLoading = false;
        if (isResponseSuccess(res)) {
          this.$message.success('提交成功')
          this.$emit('getTableData')
          this.handleCloseDialog()
        }
      });
    },
    // 清空弹框内容
    handleClearCategory () {
      this.searchCategoryList = [];
      this.treeCategoryList = [];
      this.searchList.checkList = [];
      this.clearAllCheckedNodes();
      this.closeAllExpandNodes();
      this.searchList.dataSource = [];
      this.$refs.formData.resetFields()
    },
    // 打开弹窗
    handleOpenDialog () {
      this.getLevelOneCategoryListFn();
      this.getSelectedCategoryAction();
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:visible', false);
      this.handleClearCategory()
    },
  }
};
</script>
<style lang="less" scoped>
.divider {
  margin: 10px 0;
}
.left-col {
  border-right: 1px dashed #dadada;
  padding-right: 20px;
}
.category-searchlist {
  .el-checkbox-group {
    border: 1px solid #ebeef5;
    padding-left: 5px;
    height: 200px;
    max-height: 200px;
    overflow-y: auto;
    label {
      line-height: 24px;
      &:first-child {
        margin-top: 10px;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
  }
}
/deep/ .category-tree {
  height: 400px !important;
  overflow: auto;
  margin: 10px 0px;
  border: 1px solid #ebeef5;
}
.category-tag {
  margin: 5px 0;
  .tag-text {
    display: inline-block;
    width: 440px;
    /* overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis; */
  }
}
.selected-card {
  padding: 10px;
  // border: 1px solid #ebeef5;
  margin-left: 10px;
  max-height: 700px;
  overflow: auto;
}
</style>
